package com.candy.candyuser.config;

import com.gitee.candy.utils.VisibleThreadPoolTaskExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.context.scope.refresh.RefreshScopeRefreshedEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.*;

/**
 * 利用 nacos动态配置刷新实现动态线程池
 *
 * @author suYanLong
 * @date 2022年10月11日 15:03
 */
@Slf4j
@Configuration
@RefreshScope
@EnableScheduling
public class RefreshProperties implements ApplicationListener<RefreshScopeRefreshedEvent> {

    @Value("${user.age:30}")
    String age;

    @Value("${user.name}")
    String name;

    @Value("${thread.corePoolSize:10}")
    Integer corePoolSize;

    @Autowired
    ApplicationContext applicationContext;

    @Override
    public void onApplicationEvent(RefreshScopeRefreshedEvent refreshScopeRefreshedEvent) {
        System.out.println(name);
        System.out.println(age);
        System.out.println(corePoolSize);
        System.out.println("----------->>>>" + refreshScopeRefreshedEvent.getName());

        ThreadPoolTaskExecutor executor = (ThreadPoolTaskExecutor) applicationContext.getBean("asyncTaskExecutor");
        if (executor.getCorePoolSize() != corePoolSize) {
            log.info("修改核心线程数");
            executor.setCorePoolSize(corePoolSize);
        }
    }

    @Bean(name = "asyncTaskExecutor")
    public Executor asyncServiceExecutor() {
        log.info("start asyncTaskExecutor");
        ThreadPoolTaskExecutor executor = new VisibleThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(15);
        executor.setQueueCapacity(50);
        executor.setKeepAliveSeconds(60);
        executor.setThreadNamePrefix("common-thread-pool");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

    //    @Scheduled(cron = "*/3 * * * * ?")
    public void job() {
        ThreadPoolTaskExecutor executor = (ThreadPoolTaskExecutor) applicationContext.getBean("asyncTaskExecutor");
        executor.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000l * 60);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }

}
